/* eslint-disable */
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, setTokenTime } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userId: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login 用户登录
  // this.$store.dispatch('user/login', this.loginForm)
  // 上面是调用时传入的参数,这里的传参方式是action中必须的，action中的方法首先需要接收一个
  // 与 store 实例具有相同方法和属性的 context 对象，因此你可以调用 context.commit 提交一个 mutation
  // 简化的写法就是使用解构的方式
  login ({ commit }, userInfo) {
    // 解构出用户名和密码
    // code是验证码,如果不想使用验证码验证,可以不传code
    // const { username, password, code } = userInfo
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // 调用api/user 里面的logoin方法
      // login({ username: username.trim(), password: password, code: code })
      login({ username: username.trim(), password: password })
        .then(response => {
          console.log(response)
          const { token, expireTime } = response
          // 把token存到vuex中
          commit('SET_TOKEN', token)
          // 把token存到cookies中
          setToken(token)
          // 设置token过期时间
          setTokenTime(expireTime)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 调用api/user里面的用户信息和权限信息，即便是同名，因为调用的方法不一样，他们也不会有冲突
      getInfo(state.token)
        .then(response => {
          // console.log(response)
          const { data } = response
          if (!data) {
            reject('Verification failed, please Login again.')
          }
          const { roles, name, avatar, introduction, id } = data
          // const { roles, name, introduction, id } = data
          // roles must be a non-empty array
          // roles必须是一个数组,并且不能是空的
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }
          // 把权限字段放到sessionStorage里面
          sessionStorage.setItem('codeList', JSON.stringify(roles))
          // 把对应的数据存储到vuex中去
          commit('SET_ROLES', roles)
          let userImg
          if (avatar) {
            userImg = avatar
          } else {
            userImg =
              'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          }
          commit('SET_NAME', name)
          commit('SET_USERID', id)
          commit('SET_AVATAR', userImg)
          commit('SET_INTRODUCTION', introduction)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resetRouter()

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles ({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
